/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class code5 {
    public ListNode reverseBetween(ListNode head, int left, int right) {
        ListNode cur = new ListNode(-1,head);
        for(int i=0;i<left;i++) {
            cur = cur.next;
        }
        Stack<Integer> st = new Stack<>();
        for(int i=0;i<right-left+1;i++) {
            st.push(cur.val);
            cur = cur.next;
        }
        //统计第一段
        ListNode ccur = new ListNode(-1);
        ListNode ret = ccur;
        for(int i=1;i<left;i++) {
            ccur.next = new ListNode(head.val);
            head = head.next;
            ccur = ccur.next;
        }
        //统计第二段
        for(int i=left;i<=right;i++) {
            ccur.next = new ListNode(st.pop());
            ccur = ccur.next;
        }
        //统计第三段
        while(cur != null) {
            ccur.next = new ListNode(cur.val);
            ccur = ccur.next;
            cur = cur.next;
        }
        return ret.next;
    }
}